package com.hax.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CustomLogoutHandler implements LogoutHandler {

    Logger logger = LoggerFactory.getLogger(CustomLogoutHandler.class);

    @Override
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Authentication authentication) {
        String tokenHeader = request.getHeader("Authorization");
        if (!StringUtils.hasText(tokenHeader)) {
            throw new BadCredentialsException("参数错误");
        }
        String token = tokenHeader.replace("Bearer ", "");
        //从redis中删除token
        //省略步骤 ...
        logger.info("logout token success token is {}", token);

        response.setStatus(HttpStatus.OK.value());
        try {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.getWriter().print("退出登录成功");
            //提前flush这里，如果这里不flush则在logoutOnsuccess中会做一个重定向到/login
            response.getWriter().flush();
        } catch (IOException e) {
            logger.error("logout error", e);
            throw new BadCredentialsException("退出登录失败");
        }
    }
}
